import {login, logout, getInfo} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
import Cookies from 'js-cookie'

const getDefaultState = () => {
  return {
    token: getToken(),
    user: Cookies.get('user'),
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  }
}

const actions = {
  login({commit}, userInfo) {
    const {userName, password, code} = userInfo
    return new Promise((resolve, reject) => {
      login({userName, password, code}).then(data => {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        commit('SET_USER', data.user)
        Cookies.set('user', JSON.stringify(data.user));
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      //logout(state.token).then(() => {
      removeToken() // must remove  token  first
      Cookies.remove('user');
      resetRouter()
      commit('RESET_STATE')
      resolve()
      /*}).catch(error => {
        reject(error)
      })*/
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

